const http = require('http');
const { spawn } = require('child_process');
const config = require('./config');

http.createServer(function (request, response) {
  const { 'x-gitee-token': token } = request.headers;
  if (token !== config.token) {
    response.statusCode = 401;
    return response.end('Error');
  }
  let data = '';
  request.on('data', (chunk) => {
    data += chunk;
  });
  request.on('end', () => {
    try {
      data = JSON.parse(data);
      response.end('Success');
      const {
        action,
        state,
        repository: { full_name: repository },
        target_branch: branch,
      } = data;
      const task = config.tasks.find(task => task.action === action
        && task.state === state
        && task.repository === repository
        && task.branch === branch);
      if (task) {
        console.log(task);
        const handle = spawn('sh', [task.script]);
        handle.stdout.on('data', (chunk) => {
          console.log(chunk.toString());
        });
        handle.stderr.on('data', (chunk) => {
          console.error(chunk.toString());
        });
        handle.on('error', (code) => {
          console.log(code);
        });
        handle.on('close', (code) => {
          console.log(`child process close with code ${code}`);
        });
      }
    } catch (e) {
      response.statusCode = 400;
      response.end(e.message);
    }
  });
}).listen(config.port);